/**
 * Created in 2012-3-2.
 */
package com.surekam.mnai.service.extractor;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 能将请求参数转换为URL对象的查询组成部分的构建者类型。
 * 
 * @author 吴政
 * 
 */
public class QueryHttpURLBuilder implements IHttpURLBuilder {

	private String endpoint;

	/**
	 * 请求参数表。
	 */
	private Map<String, String> requestPropertyMap;

	/**
	 * 创建一个构建者。
	 */
	public QueryHttpURLBuilder() {
		requestPropertyMap = new HashMap<String, String>();
	}

	/**
	 * @see com.surekam.mnai.service.extractor.IHttpURLBuilder#getEndpoint()
	 */
	@Override
	public String getEndpoint() {
		return endpoint;
	}

	/**
	 * @see com.surekam.mnai.service.extractor.IHttpURLBuilder#setEndpoint(java.lang.String)
	 */
	@Override
	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	/**
	 * @see com.surekam.mnai.service.extractor.IHttpURLBuilder#getRequestProperty(java.lang.String)
	 */
	@Override
	public String getRequestProperty(String key) {
		return requestPropertyMap.get(key);
	}

	/**
	 * @see com.surekam.mnai.service.extractor.IHttpURLBuilder#setRequestProperty(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public void setRequestProperty(String key, String value) {
		requestPropertyMap.put(key, value);
	}

	/**
	 * @see com.surekam.mnai.service.extractor.IHttpURLBuilder#removeRequestProperty(java.lang.String)
	 */
	@Override
	public void removeRequestProperty(String key) {
		requestPropertyMap.remove(key);
	}

	/**
	 * @see com.surekam.mnai.service.extractor.IHttpURLBuilder#clearRequestProperty()
	 */
	@Override
	public void clearRequestProperty() {
		requestPropertyMap.clear();
	}
	
	/**
	 * @see com.surekam.mnai.service.extractor.IHttpURLBuilder#getRequestProperties()
	 */
	@Override
	public Map<String, String> getRequestProperties() {
		Map<String, String> clone = new HashMap<String, String>();
		clone.putAll(requestPropertyMap);
		
		return clone;
	}

	/**
	 * @throws MalformedURLException
	 * @see com.surekam.mnai.service.extractor.IHttpURLBuilder#build()
	 */
	@Override
	public URL build() throws MalformedURLException {
		return new URL(endpoint + getQuery());
	}

	/**
	 * 获取查询部分。
	 * 
	 * @return 要创建的URL对象的查询部分
	 */
	private String getQuery() {
		if (requestPropertyMap.isEmpty()) {
			return "";
		} else {
			StringBuffer buf = new StringBuffer("?");

			for (Map.Entry<String, String> e : requestPropertyMap.entrySet()) {
				buf.append(e.getKey());
				buf.append("=");
				buf.append(e.getValue());
				buf.append("&");
			}

			buf.deleteCharAt(buf.length() - 1);

			return buf.toString();
		}
	}

}
